#include <iostream>
#include <string>
#include <cstdio>
#include "Server.hpp"
using namespace std;

// string Response(string & request)
// {
//     return request += "hello world";
// }

string Response(string &request)
{
    cout << "request : " << request << endl;
    FILE *fp = popen(request.c_str(), "r");
    if (fp == nullptr)
    {
        return "unknow request";
    }

    std::string ret;
    char buffer[1024];
    while (true)
    {
        char *s = fgets(buffer, sizeof(buffer), fp);
        if (!s)
            break;
        else
            ret += buffer;
    }
    pclose(fp);
    return ret;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        cout << "Incorrect use, correct use :" << endl
             << "        ./server local_ip local_port" << endl;
        return 1;
    }

    uint16_t port = stoi(argv[1]);

    Server server(Response, port);
    server.Init();

    server.Start();

    return 0;
}